#include <system.h>

#define timer_defaulthertz 100

int timerticks = 0;
int timerhertz = 18; // Hardware default

void timer_setspeed(int hertz)
{
 if(!hertz) hertz = 100; // Default to 100 hertz if passed a null arguement

 int divisor = 1193180/hertz; /* Calculate our divisor */
 outportb(0x43,0x36);         /* Set our command byte 0x36 */
 outportb(0x40,divisor&0xFF); /* Set low byte of divisor */
 outportb(0x40,divisor>>8);   /* Set high byte of divisor */

 timerhertz = hertz;
}

void timer_handler(struct regs* r)
{
 timerticks++;

 if (timerticks % timerhertz == 0)
 {
  // One second has passed
 }
}

/* Sets up the system clock by installing the timer handler
*  into IRQ0 */
void timer_install()
{
#if _Verbose_Init_
 vga_printstr("Clock...");
#endif

 /* Installs 'timer_handler' to IRQ0 */
 irq_install_handler(0, timer_handler);

 // Sets the clock to the kernel default
 timer_setspeed(timer_defaulthertz);

#if _Verbose_Init_
 vga_printstr("initialized.\n");
#endif
}

void timer_wait(int ticks)
{
 int i = timerticks + ticks;
 while(i > timerticks);
}
